package com.gitee.luosl.cola.match.cases;

import com.gitee.luosl.cola.match.guard.Guard;
import com.gitee.luosl.cola.match.pattern.Pattern;

/**
 * Created by luosl on 2021/04/06/9:44
 */
abstract public class AbstractCase<T, U, R> implements ICase<T, U, R> {

    private final Pattern<? super T, ? extends U> pattern;

    private final Guard<U> guard;

    public AbstractCase(Pattern<? super T, ? extends U> pattern, Guard<U> guard) {
        this.pattern = pattern;
        this.guard = guard;
    }

    @Override
    public U unapply(T value) {
        return pattern.apply(value);
    }

    @Override
    public boolean isDefinedAt(T value) {
        if(null == guard){
            return pattern.isDefinedAt(value);
        }
        return pattern.isDefinedAt(value) && guard.test(unapply(value));
    }
}
